package com.mall.user.services;


import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.EmailService;
import com.mall.user.IRegisterService;
import com.mall.user.config.MailSourceProperties;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;

import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 创建日期: 2022-01-19-22-31
 * author : WQW
 * description: 用户注册
 */
@Slf4j
@Service
public class RegisterServiceImpl implements IRegisterService {


    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    MailSourceProperties mailSourceProperties;

    @Reference
    EmailService emailService;

    /**
     * @param
     * @param request
     * @return com.mall.user.dto.RegisterMemberRespone
     * @description 根据用户注册信息，注册新用户
     * @author WQW
     * @date 2022/1/19 22:55
     */

    @Override
    @Transactional
    public UserRegisterResponse registerMember(UserRegisterRequest request) {
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        try {
            // 1.参数校验
            request.requestCheck();
            // 2.验证用户名是否重复
            verifyUsernameUnique(request.getUserName());
            // 3.向用户表中插入一条记录
            Member member = new Member();
            member.setUsername(request.getUserName());
            // 对用户密码使用MD5进行加密
            String encryptedPassword = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
            member.setPassword(encryptedPassword);
            member.setEmail(request.getEmail());
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setState(1);
            int result1 = memberMapper.insert(member);
            if (result1 != 1) {
                userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return userRegisterResponse;
            }

            // 4.向用户验证表中插入一条记录
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            // 获取uuid
            // 这里使用用户名、密码和UUID随机生成的字符串进行拼接，再使用MD5加密生成uuid
            String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            int result2 = userVerifyMapper.insert(userVerify);
            if (result2 != 1) {
                userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return userRegisterResponse;
            }
            // 5.发送用户激活邮件
            emailService.senderEmail(uuid, request);
            userRegisterResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            log.info("用户注册成功，注册参数requst:{}", JSON.toJSONString(request));
        }catch (Exception e){
            log.error("LoginServiceImpl.login occur Exception :"+ e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionProcessorUtils.wrapperHandlerException(userRegisterResponse,e);
        }
        return userRegisterResponse;
    }


    /**
     * @param
     * @param userName
     * @return void
     * @description 验证用户名是否唯一
     * @author WQW
     * @date 2022/1/20 10:11
     */
    private void verifyUsernameUnique(String userName) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userName);
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
//=======
// * 用户注册实现类
// * 创建日期: 2022/01/20 20:54
// *
// * @author ghr
// */
//@Service
//@Slf4j
//public class RegisterServiceImpl implements IRegisterService {
//    @Autowired
//    private MemberMapper memberMapper;
//
//    @Autowired
//    private UserVerifyMapper userVerifyMapper;
//
//    @Override
//    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
//        UserRegisterResponse response = new UserRegisterResponse();
//
//        registerRequest.requestCheck();
//
//        //验证用户是否重复
//        volidUserNameRepeat(registerRequest);
//        //1. 向用户表中插入一条记录
//        Member member = new Member();
//        member.setUsername(registerRequest.getUserName());
//        member.setEmail(registerRequest.getEmail());
//        String md5Pwd = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
//        member.setPassword(md5Pwd);
//        member.setCreated(new Date());
//        member.setUpdated(new Date());
//        member.setIsVerified("N");
//        member.setState(1);
//        int effectRows = memberMapper.insert(member);
//        if (effectRows != 1) {
//            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
//            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
//            return response;
//        }
//        //2. 向用户验证表中插入一条记录
//        UserVerify userVerify = new UserVerify();
//        userVerify.setUsername(member.getUsername());
//        String key = member.getUsername()+member.getPassword()+ UUID.randomUUID().toString();
//        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
//        userVerify.setUuid(uuid);
//        userVerify.setRegisterDate(new Date());
//        userVerify.setIsExpire("N");
//        userVerify.setIsVerify("N");
//        int rows = userVerifyMapper.insert(userVerify);
//        if (rows != 1) {
//            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
//            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
//            return response;
//        }
//        //3. 发送用户激活邮件
//        //TODO 发送用户激活邮件
//
//        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//        return response;
//    }
//
//    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
//        Example example = new Example(Member.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("username",registerRequest.getUserName());
//        List<Member> memberList = memberMapper.selectByExample(example);
//        if (!CollectionUtils.isEmpty(memberList)) {
//            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
//        }
//    }
//}
//>>>>>>> 7680e2744854195de05ee0321542558e3065dc85
















































//package com.mall.user.services;
//
//import com.mall.commons.tool.exception.ValidateException;
//import com.mall.user.IRegisterService;
//import com.mall.user.constants.SysRetCodeConstants;
//import com.mall.user.dal.entitys.Member;
//import com.mall.user.dal.entitys.UserVerify;
//import com.mall.user.dal.persistence.MemberMapper;
//import com.mall.user.dal.persistence.UserVerifyMapper;
//import com.mall.user.dto.UserRegisterRequest;
//import com.mall.user.dto.UserRegisterResponse;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.dubbo.config.annotation.Service;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.util.CollectionUtils;
//import org.springframework.util.DigestUtils;
//import tk.mybatis.mapper.entity.Example;
//
//import java.util.Date;
//import java.util.List;
//import java.util.UUID;
//
///**
// * 用户注册实现类
// * 创建日期: 2022/01/20 20:54
// *
// * @author ghr
// */
//@Service
//@Slf4j
//public class RegisterServiceImpl implements IRegisterService {
//    @Autowired
//    private MemberMapper memberMapper;
//
//    @Autowired
//    private UserVerifyMapper userVerifyMapper;
//
//    @Override
//    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
//        UserRegisterResponse response = new UserRegisterResponse();
//
//        registerRequest.requestCheck();
//
//        //验证用户是否重复
//        volidUserNameRepeat(registerRequest);
//        //1. 向用户表中插入一条记录
//        Member member = new Member();
//        member.setUsername(registerRequest.getUserName());
//        member.setEmail(registerRequest.getEmail());
//        String md5Pwd = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
//        member.setPassword(md5Pwd);
//        member.setCreated(new Date());
//        member.setUpdated(new Date());
//        member.setIsVerified("N");
//        member.setState(1);
//        int effectRows = memberMapper.insert(member);
//        if (effectRows != 1) {
//            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
//            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
//            return response;
//        }
//        //2. 向用户验证表中插入一条记录
//        UserVerify userVerify = new UserVerify();
//        userVerify.setUsername(member.getUsername());
//        String key = member.getUsername()+member.getPassword()+ UUID.randomUUID().toString();
//        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
//        userVerify.setUuid(uuid);
//        userVerify.setRegisterDate(new Date());
//        userVerify.setIsExpire("N");
//        userVerify.setIsVerify("N");
//        int rows = userVerifyMapper.insert(userVerify);
//        if (rows != 1) {
//            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
//            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
//            return response;
//        }
//        //3. 发送用户激活邮件
//        //TODO 发送用户激活邮件
//
//        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//        return response;
//    }
//
//    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
//        Example example = new Example(Member.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("username",registerRequest.getUserName());
//        List<Member> memberList = memberMapper.selectByExample(example);
//        if (!CollectionUtils.isEmpty(memberList)) {
//            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
//        }
//    }
//}